package com.css.fxfzfxqh.modules.reportmanagement.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzfxqh.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzfxqh.base.attachment.service.AttachmentInfoService;
import com.css.fxfzfxqh.base.response.RestResponse;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.repository.*;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.casualtiesDE.entity.PCC;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.publicOperate.service.DistrictService;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.publicOperate.service.PublicOperateService;
import com.css.fxfzfxqh.modules.downloadLegend.service.SupergraphService;
import com.css.fxfzfxqh.modules.lifelineEngineering.entity.EvaluationResults;
import com.css.fxfzfxqh.modules.lifelineEngineering.entity.LifelineTaskEntity;
import com.css.fxfzfxqh.modules.lifelineEngineering.repository.EstimateRepository;
import com.css.fxfzfxqh.modules.lifelineEngineering.repository.TaskManagementRepository;
import com.css.fxfzfxqh.modules.reportmanagement.legend.*;
import com.css.fxfzfxqh.modules.reportmanagement.reportutil.DownloadsFile;
import com.css.fxfzfxqh.modules.reportmanagement.service.GraphService;
import com.css.fxfzfxqh.modules.reportmanagement.vo.LegendVo;
import com.css.fxfzfxqh.modules.reportmanagement.vo.RequestVO;
import com.css.fxfzfxqh.modules.reportmanagement.vo.ResponseVO;
import com.css.fxfzfxqh.modules.reportmanagement.vo.StructureVO;
import com.css.fxfzfxqh.modules.util.repository.PccRepository;
import com.css.fxfzfxqh.util.PlatformObjectUtils;
import com.css.fxfzfxqh.util.RestTemplateUtil;
import com.css.fxfzfxqh.util.UUIDGenerator;
import com.css.fxfzfxqh.zcpt.sys.service.SysAreaService;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.data.PictureType;
import com.deepoove.poi.data.Pictures;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import com.google.common.collect.TreeBasedTable;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slw.common.helper.PropsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class GraphServiceImpl implements GraphService {

    @Value("${image.ctLocalDir}")
    private String ctLocalDir;
    @Resource
    private DownloadsFile downloadsFile;
    @Resource
    RestTemplateUtil restTemplateUtil;
    @Resource
    RestTemplate restTemplate;
    @Autowired
    private AttachmentInfoService attachmentInfoService;

    @Resource
    PccRepository pccRepository;

    @Resource
    TaskManagementRepository taskManagementRepository;

    @Resource
    JdbcTemplate jdbcTemplate;

    @Resource
    PublicOperateService publicOperateService;

    @Resource
    EstimateRepository estimateRepository;

    @Value("${hypergraph.iServerHttp}")
    String iServerHttp;

    @Resource
    FxqhBuildingGridUrbanSteelConcreteRepository fxqhBuildingGridUrbanSteelConcreteRepository;
    @Resource
    FxqhBuildingGridUrbanSteelRepository  fxqhBuildingGridUrbanSteelRepository;
    @Resource
    FxqhBuildingGridUrbanMasonryRepository fxqhBuildingGridUrbanMasonryRepository;
    @Resource
    FxqhBuildingGridUrbanOtherRepository fxqhBuildingGridUrbanOtherRepository;
    @Resource
    FxqhBuildingGridRuralWoodBambooRepository fxqhBuildingGridRuralWoodBambooRepository;
    @Resource
    FxqhBuildingGridRuralSteelConcreteRepository fxqhBuildingGridRuralSteelConcreteRepository;
    @Resource
    FxqhBuildingGridRuralSteelRepository fxqhBuildingGridRuralSteelRepository;
    @Resource
    FxqhBuildingGridRuralOtherRepository fxqhBuildingGridRuralOtherRepository;
    @Resource
    FxqhBuildingGridRuralMixedRepository fxqhBuildingGridRuralMixedRepository;
    @Resource
    FxqhBuildingGridRuralMasonryRepository fxqhBuildingGridRuralMasonryRepository;
    @Resource
    FxqhBuildingGridRuralCivilRepository fxqhBuildingGridRuralCivilRepository;
    @Resource
    FxqhBuildingGridRuralBottomFrameRepository fxqhBuildingGridRuralBottomFrameRepository;
    @Resource
    FxqhBuildingGridUrbanWoodRepository fxqhBuildingGridUrbanWoodRepository;
    @Resource
    DistrictService districtService;
    @Resource
    SysAreaService sysAreaService;
    @Resource
    SupergraphService supergraphService;

    public RestResponse generateGraph(RequestVO requestVO,String taskId,MapTemplate mapTemplate) {
        String fileName = mapTemplate.getDictCode();
        RestResponse restResponse = null;
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String url = configGroup.getProperty("supergraphRestTemplateUrl") + "/webprinting/rest/webprinting/v1/jobs.json";
        JSONObject requestJsonVo = (JSONObject) JSONObject.toJSON(requestVO);
        String json = JSONObject.toJSONString(requestJsonVo);
        log.info(json);
        Map map = JSONObject.parseObject(json, Map.class);
        ResponseEntity<String> stringResponseEntity = restTemplateUtil.sendPostHttpRequest(url, map);
        String body = stringResponseEntity.getBody();
        List<ResponseVO> responseVO = JSON.parseArray(body, ResponseVO.class);
        String path = "";
        if (responseVO != null || responseVO.size() > 0) {
            path = responseVO.get(0).getPath();
            //获取出图任务状态
            path = getMapLayerPrintJob(path);
            if(path.equals("出图失败")){
                return RestResponse.fail("出图失败！");
            }
            path = responseVO.get(0).getPath() + "/" + "result";
            String savePath = ctLocalDir;
            path = path.replace("@", "%40");
            System.out.println("路径  " + path);
            restResponse = downloadsFile.downloadByUrl(path, savePath,taskId,fileName,mapTemplate.getFlag());
        }
        File file = new File(ctLocalDir);
        File[] files = file.listFiles();
        for (File file1 : files) {
            if (file1.isFile()) {
                file1.delete();
            }
        }

        return restResponse;
    }
    //获取出图任务状态
    private String getMapLayerPrintJob(String path) {
        String result = null;
        try {
            String dataUrl = path + ".json";
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return "出图失败";
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(new JSONObject(), headers);
            ResponseEntity<JSONObject> exchange = restTemplate.exchange(dataUrl, HttpMethod.GET, entity, JSONObject.class);
            JSONObject body = exchange.getBody();
            /*if (body == null) {
                return "出图失败";
            }*/
            if (body.getString("status").equals("ERROR")) {
                return "出图失败";
            }
            while (!body.getString("status").equals("ERROR") && !body.getString("status").equals("FINISHED")) {
                Thread.sleep(1000);
                //获取任务执行百分比
                result = getMapLayerPrintJob(path);
                if(result.equals("出图成功") || result.equals("出图失败")){
                    break;
                }
            }
            if(body.getString("status").equals("FINISHED")){
                return "出图成功";
            }else if (body.getString("status").equals("ERROR")) {
                return "出图失败";
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = getMapLayerPrintJob(path);
        }
        return result;
    }
    public String getExtent(String dataVersion) {
        String extent = null;
        try{
            String sql="select ST_extent ( geom ) from fxqh_setting_seismic_influenceflied where version_code='"+dataVersion+"'  and del_flag='0'";
            extent=jdbcTemplate.queryForObject(sql,String.class);
        }catch (Exception e){
            e.printStackTrace();
        }
        return extent;
    }
    public String getExtent(List<PCC> pccList) {
        String extent = null;
        try{
            String geom = publicOperateService.getUnionGeomByCode(pccList);
            log.info("geom>>>>",geom);
//            String sql ="select ST_extent(?) as geom";
            String sql="select ST_extent ( st_geometryfromtext(?,4490) ) ";
            extent=jdbcTemplate.queryForObject(sql,String.class,geom);
        }catch (Exception e){
            e.printStackTrace();
        }
        return extent;
    }
    public String getCenter(String dataVersion) {
        String center=null;
        //List<PCC> pccList = getPCCDataQueryParam(taskId);
        try{
            String sql ="select ST_AsText(ST_Centroid(ST_extent(geom )))  as geom  from fxqh_setting_seismic_influenceflied where version_code='"+dataVersion+"' and del_flag='0'";
            center=jdbcTemplate.queryForObject(sql,String.class);
        }catch (Exception e){
            e.printStackTrace();
        }
        return center;
    }
    public String getCenter(List<PCC> pccList) {
        String center=null;
        //List<PCC> pccList = getPCCDataQueryParam(taskId);
        try{
            String geom = publicOperateService.getUnionGeomByCode(pccList);
            String sql ="select ST_AsText(ST_Centroid(ST_extent(st_geometryfromtext(?,4490) )))  as geom  ";
            center=jdbcTemplate.queryForObject(sql,String.class,geom);
        }catch (Exception e){
            e.printStackTrace();
        }
        return center;
    }

    @Override
    public String getExtent(Map<String, Object> paramMap) {
        String extent = null;
        if(paramMap!=null && paramMap.containsKey("province") && paramMap.containsKey("city")&& paramMap.containsKey("county")){
            StringBuilder sb  = new StringBuilder();
            sb.append("select ST_extent(a.geom) as geom                                                        ");
            sb.append("from district_boundary_county a                                                         ");
            sb.append("left join district_boundary_city b on b.code=concat(subString(a.code,0,5),'00')         ");
            sb.append("left join district_boundary_province c on c.code=concat(subString(a.code,0,3),'0000')   ");
            sb.append("where c.name=? and b.name=? and a.name=?                           ");
            String provinceName = paramMap.get("province").toString();
            String cityName=paramMap.get("city").toString();
            String countyName=paramMap.get("county").toString();
            extent = jdbcTemplate.queryForObject(sb.toString(),String.class,provinceName,cityName,countyName);
        }
        return extent;
    }

    @Override
    public String getCenter(Map<String, Object> paramMap) {
        String center=null;
        if(paramMap!=null && paramMap.containsKey("province") && paramMap.containsKey("city")&& paramMap.containsKey("county")) {
            StringBuilder sb = new StringBuilder();
            sb.append("select  ST_AsText(ST_Centroid(ST_extent(a.geom)))  as geom                                ");
            sb.append("from district_boundary_county a                                                           ");
            sb.append("left join district_boundary_city b on b.code=concat(subString(a.code,0,5),'00')           ");
            sb.append("left join district_boundary_province c on c.code=concat(subString(a.code,0,3),'0000')     ");
            sb.append("where c.name=? and b.name=? and a.name=?                             ");
            String provinceName = paramMap.get("province").toString();
            String cityName=paramMap.get("city").toString();
            String countyName=paramMap.get("county").toString();
            center = jdbcTemplate.queryForObject(sb.toString(), String.class, provinceName, cityName, countyName);
        }
        return center;
    }

    private List<PCC> getPCCDataQueryParam(String taskId){
        StringBuilder sb = new StringBuilder();
        sb.append("select t2.pp_name ,t2.city_name   ,t2.NAME     ");
        sb.append("from fxqh_calculation_tasks t1                                           ");
        sb.append("left join fxqh_assess_toponym t2  on t1.id=t2.assess_id                  ");
        sb.append("where t1.id=?                       ");
        List<PCC> pccList = jdbcTemplate.query(sb.toString(),new BeanPropertyRowMapper<>(PCC.class),taskId);
        return pccList;
    }
    /**
     * 根据任务ID 查询的省、市、县
     * @param taskId
     * @return
     */
    private Map<String,Object> getProvinceCityCountyDataQueryParam(String taskId){
       StringBuilder sb = new StringBuilder();
        sb.append("select t2.pp_name as province,t2.city_name as city  ,t2.NAME as county    ");
        sb.append("from fxqh_calculation_tasks t1                                           ");
        sb.append("left join fxqh_assess_toponym t2  on t1.id=t2.assess_id                  ");
        sb.append("where t1.id=?   limit 1                       ");
        Map<String,Object> map = jdbcTemplate.queryForMap(sb.toString(),taskId);
        return map;
    }

    /**
     * 查询网格数据  结构类型，字典dictCode 值
     * @param taskId
     * @return
     */
    @Override
    public List<Map<String,Object>> getGridDataStructureTypeList(String taskId){
        String sql="select distinct dictionary as dict_code,structure_type from fxqh_grid_data_copy where task_id=? ";
        List<Map<String,Object>> list =jdbcTemplate.queryForList(sql,taskId);
        return list;
    }
//    @Override
//    public List<Map<String,String>>  buildGridCategoryGraphParamData(String taskId){
//        List<Map<String,Object>> mapList = getGridDataStructureTypeList(taskId);
//        List<Map<String,String>> resultList = new ArrayList<>();
//        for(Map<String,Object> dataMap:mapList){
//            Map<String,String> map = buildGridDataGraphParam(taskId,dataMap.get("dict_code").toString(),"");
//            if(map!=null){
//                resultList.add(map);
//            }
//        }
//        return resultList;
//    }

    public static void main(String[] args) {
        TreeBasedTable<Integer, String, Integer> table = TreeBasedTable.create();

        table.put(2, "2", 6);
        table.put(3, "3", 4);
        table.put(1, "1", 5);
        table.put(5, "5", 2);
        table.put(4, "4", 2);
        table.put(6, "6", 9);
        table.rowComparator();
        Map<Integer,Map<String,Integer>> rowMap = table.rowMap();
        rowMap.forEach(
                (k, v) -> {
                    v.forEach(
                            (a, b) -> {
                                System.out.println(k + "," + a + "," + b);
                            });
                });
    }
    //获取磁盘上的超图文件
    public Map<String,Object> getAllFiles(String taskId,String flag,String type){
        Map<String,Object> fileMap = new HashMap<>();
        String filepath = ctLocalDir + File.separator + taskId;
        // File类型可以是文件也可以是文件夹
        File file = new File(filepath);
        //得到所有文件
        if(!file.isDirectory() || !file.exists()){
            return null;
        }
        if(!"5".equals(flag) && !"6".equals(flag)){
            //非生命线工程 获取公共图件和各自私有的图件
            getChildrenFile(file,fileMap,flag,type);
        }else if("5".equals(flag)  || "6".equals(flag)){
            //生命线工程 只获取各自私有的图件
            File file1 = new File(filepath+File.separator+flag);
            if(!file1.exists() || !file1.isDirectory()){
                return fileMap;
            }else{
                getChildrenFile1(file1,fileMap);
            }
        }
        return fileMap;
    }
    private void getChildrenFile(File file,Map<String,Object> fileMap,String flag,String type){
        for (File file2 : Objects.requireNonNull(file.listFiles())) {
            //是否为文件
            if (file2.isFile()) {
                String prefix = FileUtil.getPrefix(file2.getName());
                fileMap.put(prefix,file.getAbsolutePath() +File.separator + file2.getName());
            }
            //当为概率评估为不查子文件夹，只查自己的
            if(StringUtils.isNotBlank(type)) {
                //概率评估-发生/超越概率时会先查公用的，此时flag和tyoe会相同
                if (flag.equals(type)) {
                    if (file2.isDirectory() && (flag.equals(file2.getName()))) {
                        getChildrenFile(file2, fileMap, flag, type);
                    }
                } else {
                    //其他类型的都查
                    if (file2.isDirectory() && (flag.equals(file2.getName()) || type.equals(file2.getName()))) {
                        getChildrenFile(file2, fileMap, flag, type);
                    }
                }
            }
        }
    }
    private void getChildrenFile1(File file,Map<String,Object> fileMap){
        for (File file2 : Objects.requireNonNull(file.listFiles())) {
            //是否为文件
            if (file2.isFile()) {
                String prefix = FileUtil.getPrefix(file2.getName());
                fileMap.put(prefix,file.getAbsolutePath() +File.separator + file2.getName());
            }
        }
    }

    //删除之前生成的超图文件(公用文件和专用文件)
    @Override
    public int  deleteAllMapTemplate(String taskId, String flag){
        String filePath = ctLocalDir + File.separator + taskId;
        if(!"4".equals(flag)){
            String flagFilePath = filePath+File.separator+flag;
            if(!new File(flagFilePath).exists()){
                new File(flagFilePath).mkdir();
            }
        }
//        Integer count = getPublicMapTemplateCount(logo);
//        String path = filePath+File.separator+logo;
//        return deleteChildFile(filePath,flag,count,path,0);
        return deleteFile(filePath,flag);
    }
    private Integer deleteFile(String filePath,String flag){
        List<Integer> numList = new ArrayList<>();
        Integer result = 0;
        File directory = new File(filePath);
        File[] files = directory.listFiles();
        if (PlatformObjectUtils.isNotEmpty(files)) {
            for (File file : files) {
                if("4".equals(flag)){
                    file.delete();
                    numList = new ArrayList<>(1);
                    numList.add(1);
                }else{
                    result = getDeleteChildFile(file,result,flag);
                    if(result>0 && !numList.contains(result)){
                        numList.add(result);
                    }
                }
            }
        }
        if(numList.size()==0){
            //表示什么也没删除
            return 0;
        }else if(numList.size()==1){
            //表示公用或私用的有一个被删除
            return numList.get(0);
        }
        //表示公用和私有的都诶删除了
        return numList.get(0)+numList.get(1);

    }
    private Integer getDeleteChildFile(File file,int result,String flag){
        String name = "4".equals(flag)?"4":file.getName();
        Integer count = getPublicMapTemplateCount(name);
        try{
            if(file.listFiles().length!=count){
                for (File f : file.listFiles()) {
                    f.delete();
                }
                //表示删除了公用的图件数据
                if(file.getName().contains("0")){
                    result = 1;
                }else{
                    //删除了各自私有的
                    result = 2;
                }
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }

        return result;
    }
    private int deleteChildFile(String filepath,String flag,Integer count,String path,int result){
        File directory = new File(filepath);
        File[] files = directory.listFiles();
        if(PlatformObjectUtils.isNotEmpty(files) && files.length>0){
            int length = files.length;
            if (PlatformObjectUtils.isNotEmpty(files)) {
                for (File file : files) {
                    if(file.isFile()){
                        //如果从数据获取到的公用的数量不等于磁盘中保存的图件的数量则删除磁盘图件,否则不删除
                        if(filepath.equals(path) && length!=count){
                            file.delete();
                            result = 1;
                        }
                        if(!filepath.equals(path)){
                            //删除独有的图件
                            file.delete();
                        }
                    }
                    String fileName = file.getName();
                    int index = file.getName().lastIndexOf("\\");
                    if(file.isDirectory() ){
                        length = length-1;
                        fileName = fileName.substring(index+1);
                        if(flag.equals(fileName) || "0-0".equals(fileName) || "0-1".equals(fileName)){
                            result = deleteChildFile(file.getAbsolutePath(),flag,0,path,result);
                        }
                    }
                }
            }
        }
        return result;
    }


    @Override
    public Map<String,Object>  buildCategoryGraphParamData(String taskId,String flag) throws Exception{
        Map<String,Object> resultMap = new HashMap<>();
        List<String> paramList = new ArrayList<>();
        paramList.add(flag);
        Map<String,Object> taskObjById = null;
        //0为单体数据1为网格数据
        String houseDataFlag = "";
        String logo = "";
        if("5".equals(flag) || "6".equals(flag)){
            taskObjById = getSmxTaskObjById(taskId);
        }else{
            taskObjById = getTaskObjById(taskId);
            houseDataFlag = taskObjById.get("house_data_flag").toString();
            //0表示公共图件，生命线工程的只有私有图件，不需要查询公共图件
            if(StringUtils.isNotBlank(houseDataFlag)){
                if("0".equals(houseDataFlag)){
                    logo = "0-0";
                }else if("1".equals(houseDataFlag)){
                    logo = "0-1";
                }
                //单独为概率评估-发生/超越概率时特别处理 其他类型的不走该逻辑
                if(!paramList.contains(logo)){
                    paramList.add(logo);
                }
            }
        }
        List<Map<String,Object>> mapList = getMapTemplateList(paramList);
        Map<String, Object> picMap = getAllFiles(taskId,flag,logo);
        int size = picMap==null?0:picMap.keySet().size();
        //比对磁盘库中生成的图件的数量和数据库中保存的需要生成图件的数据量如果一致则获取磁盘上的图件，否则删除磁盘上的图件调用超图重新生成图件到磁盘上
        if(size!=mapList.size()){
            //表示需要的图件没有完全生成，需要重新生成
            int result = -1;
            if(size>0){
                result = deleteAllMapTemplate(taskId,flag);
            }
            List<Map<String,Object>> tempList = new ArrayList<>();
            if(result==0){
                //0 表示磁盘上的文件一个都没删除，不需要调用超图重新生成图件
                tempList = new ArrayList<>();
                resultMap = picMap;
            } else if(result==3 || result == -1){
                //3 表示磁盘上的文件都被删除，都需要调用超图重新生成图件
                tempList = mapList;
            }else if(result==1){
                //1 表示删除了共有的，私有的没被删除
                for (Map<String, Object> map : mapList) {
                    Object flag1 = map.get("flag");
                    if(PlatformObjectUtils.isNotEmpty(flag1) && logo.equals(flag1.toString())){
                        tempList.add(map);
                    }
                }
            }else if(result==2){
                //2 表示删除了私有的，共有的没被删除
                for (Map<String, Object> map : mapList) {
                    Object flag1 = map.get("flag");
                    if(PlatformObjectUtils.isNotEmpty(flag1) && flag.equals(flag1.toString())){
                        tempList.add(map);
                    }
                }
            }
            if(tempList.size()>0){
//                String unionGeom = "";
//                List<PCC> pcces = pccRepository.queryToponym(taskId);
//                if(PlatformObjectUtils.isNotEmpty(pcces)){
//                    List<String> idList = pcces.stream().map(pcc -> {
//                        return pcc.getId();
//                    }).collect(Collectors.toList());
//                    if(PlatformObjectUtils.isNotEmpty(idList)){
//                        List<String> codeList = new ArrayList<>();
//                        for (String id : idList) {
//                            String code = sysAreaService.getDivisionCodeById(id);
//                            code =(String) JSONObject.parse(code);
//                            codeList.add(code);
//                        }
//                        if(codeList.size()>0){
//                            try{
//                                unionGeom = districtService.getUnionGeomByCodeList(codeList);
//                            }catch (Exception ex){
//                                throw new RuntimeException("获取报告失败，获取区县空间数据失败");
//                            }
//                        }
//                    }
//                }
                for(Map<String,Object> dataMap:tempList){
                    Map<String,String> map = new HashMap<>();
                    try{
                        String dictCode = dataMap.get("dict_code").toString();
//                        String type = dataMap.get("flag").toString();
//
//                        //房屋数据版本   建筑物单体或格网数据
//                        if(dictCode.endsWith("gw") && type.contains("0-")){
//                            String houseVersion = taskObjById.get("house_data").toString();
//                            if(StringUtils.isNotBlank(unionGeom)){
//                                //获取指定版本下某个空间数据下的数据
//                                Integer num = getGridNumByVesrion(houseVersion,dictCode,unionGeom);
//                                if(num>0){
//                                    map = buildGridDataGraphParam(taskId,dictCode,dataMap.get("flag").toString(),flag);
//                                }
//                            }
//                        }else{
                            map = buildGridDataGraphParam(taskId,dictCode,dataMap.get("flag").toString(),flag);
                        //}
                    }catch (NullPointerException ex){
                        ex.printStackTrace();
                    }

                    if(PlatformObjectUtils.isNotEmpty(map)){
                        String fileId = map.get("fileId");
                        AttachmentInfoEntity entity = attachmentInfoService.getAttach(fileId);
                            String filePath = entity.getFileDirId()+File.separator+entity.getAttachPath();
                            resultMap.put(map.get("imageName"),filePath);
                    }
                }
                //如果只生成私有的（或共有的）返回的map也只包含私有的（共有的），如果是非生命线工程的则需要再加上公共（私有的）的图件
                if(result==1 || result==2){
                    Iterator<Map.Entry<String, Object>> iterator = picMap.entrySet().iterator();
                    while(iterator.hasNext()){
                        Map.Entry<String, Object> next = iterator.next();
                        resultMap.put(next.getKey(),next.getValue());
                    }
                }
            }
        }else{
            resultMap = picMap;
        }
        for (Map<String, Object> entity : mapList) {
            String dictCode = entity.get("dict_code").toString();
            if(!resultMap.containsKey(dictCode)){
                resultMap.put(dictCode,"/data/fxqh/static/图片1.png");
            }
        }
        return resultMap;
        //return handleHouseData(resultMap);
    }

    //动态处理建筑物单体、格网数据
    private Map<String,Object> handleHouseData(Map<String,Object> resultMap){
        Map<String,Object> map = new HashMap<>(resultMap.values().size());

//        table.rowComparator();
//        Map<Integer,Map<String,String>> rowMap = table.rowMap();
//        rowMap.forEach(
//                (k, v) -> {v.forEach((a, b) -> {
//                    if(k<3){
//                        Map<String, Object> data = new HashMap<String, Object>(2);
//                        String title = (k+1)+"";
//                        title = "图1-1-"+title+" "+a;
//                        data.put("title",title);
//                        PictureRenderData picImg = null;
//                        try {
//                            picImg = Pictures.ofStream(new FileInputStream(b), PictureType.PNG).altMeta("图片不存在")
//                                    .size(580, 380).create();
//                        } catch (FileNotFoundException e) {
//                            e.printStackTrace();
//                        }
//                        data.put("structurePicture",picImg);
//                        structure.add(data);
//                    }
//
//                    });
//                });
//        map.put("structure",structure);
        return map;
    }



    private Integer getGridNumByVesrion(String houseVersion,String dictCode,String geom) {
        Integer num = 0;
        switch (dictCode){
            case "czghjggw":
                num = fxqhBuildingGridUrbanSteelConcreteRepository.listGridDataNumByVersionCode(houseVersion,geom);
                break;
            case "czgjggw":
                num = fxqhBuildingGridUrbanSteelRepository.listGridDataNumByVersionCode(houseVersion,geom);
                break;
            case "czqtjggw":
                num = fxqhBuildingGridUrbanMasonryRepository.listGridDataNumByVersionCode(houseVersion,geom);
                break;
            case "czqtjglxgw":
                num = fxqhBuildingGridUrbanOtherRepository.listGridDataNumByVersionCode(houseVersion,geom);
                break;
            case "ncmzjggw":
                num = fxqhBuildingGridRuralWoodBambooRepository.listGridDataNumByVersionCode(houseVersion,geom);
                break;
            case "ncghjggw":
                num = fxqhBuildingGridRuralSteelConcreteRepository.listGridDataNumByVersionCode(houseVersion,geom);
                break;
            case "ncgjggw":
                num = fxqhBuildingGridRuralSteelRepository.listGridDataNumByVersionCode(houseVersion,geom);
                break;
            case "ncqtjglxgw":
                num = fxqhBuildingGridRuralOtherRepository.listGridDataNumByVersionCode(houseVersion,geom);
                break;
            case "nchzjggw":
                num = fxqhBuildingGridRuralMixedRepository.listGridDataNumByVersionCode(houseVersion,geom);
                break;
            case "ncqtjggw":
                num = fxqhBuildingGridRuralMasonryRepository.listGridDataNumByVersionCode(houseVersion,geom);
                break;
            case "nctmsmjggw":
                num = fxqhBuildingGridRuralCivilRepository.listGridDataNumByVersionCode(houseVersion,geom);
                break;
            case "ncdbkjkzqqtjggw":
                num = fxqhBuildingGridRuralBottomFrameRepository.listGridDataNumByVersionCode(houseVersion,geom);
                break;
            case "czmjggw":
                num = fxqhBuildingGridUrbanWoodRepository.listGridDataNumByVersionCode(houseVersion,geom);
                break;
            default:
                num = 0;
        }
        return num;
    }

    @Override
    public Map<String,Object>  buildCategoryGraphParamDataPlus(String taskId,String flag,String[] years) throws Exception {
        Map<String,Object> resultMap = new HashMap<>();
        List<Map<String,Object>> mapList = getMapTemplateList(Arrays.asList(flag));
        String filePathTemp=taskId+"_4";
        Map<String,Object> taskObjById = getTaskObjById(taskId);
        Map<String, Object> picMap = getAllFiles(filePathTemp,flag,"");
        int size = picMap==null?0:picMap.keySet().size();
        if(size!=(mapList.size()*years.length)){
            //表示需要的图件没有完全生成，需要重新生成
            int result = -1;
            if(size>0){
                result = deleteAllMapTemplate(filePathTemp,flag);
            }

            List<Map<String,Object>> tempList = new ArrayList<>();
            if(result==0){
                for (Map<String, Object> map : mapList) {
                    Object flag1 = map.get("flag");
                    if(PlatformObjectUtils.isNotEmpty(flag1) && flag.equals(flag1.toString())){
                        tempList.add(map);
                    }
                }
            }else{
                tempList = mapList;
            }
            for(Map<String,Object> dataMap:tempList){
                List<Map<String, String>> dzbJgph4Fzgv = getCommonDataMapParamDataPlus(taskId, dataMap.get("dict_code").toString(), years,flag);
                for (Map<String, String> stringStringMap : dzbJgph4Fzgv) {
                    if(PlatformObjectUtils.isNotEmpty(stringStringMap)){
                        String fileId = stringStringMap.get("fileId");
                        AttachmentInfoEntity entity = attachmentInfoService.getAttach(fileId);
                        String filePath = entity.getFileDirId()+File.separator+entity.getAttachPath();
                        resultMap.put(stringStringMap.get("imageName"),filePath);
                    }
                }
            }
            if(result==0){
                Iterator<Map.Entry<String, Object>> iterator = picMap.entrySet().iterator();
                while(iterator.hasNext()){
                    Map.Entry<String, Object> next = iterator.next();
                    resultMap.put(next.getKey(),next.getValue());
                }
            }
        }else{
            resultMap = picMap;
        }

        return resultMap;
    }
    private List<Map<String, Object>> getMapTemplateList(List<String> flagList) {
        String sql="select * from sys_map_tempate where flag in ('"+String.join("','", flagList)+"') order by sort";
        return jdbcTemplate.queryForList(sql);
    }

    private Integer getPublicMapTemplateCount(String logo){
        String sql="select count(*) from sys_map_tempate where flag ='"+logo+"'";
        return jdbcTemplate.queryForObject(sql,Integer.class);
    }

    /**
     * 构造生产图例的参数对象
     * @param taskId
     * @param dictCode
    czqtjggw	城镇砌体结构房屋格网
    czghjggw	城镇钢混结构房屋格网
    czgjggw	城镇钢结构房屋格网
    czmjggw	城镇木结构房屋格网
    czqtjglxgw	城镇其他结构房屋格网
    ncqtjggw	农村砌体结构房屋格网
    nctmsmjggw	农村土木石木结构房屋格网
    ncdbkjkzqqtjggw	农村底部框架结构房屋格网
    ncmzjggw	农村木竹结构房屋格网
    nchzjggw	农村混杂结构房屋格网
    ncghjggw	农村钢混结构房屋格网
    ncgjggw	农村钢结构房屋格网
     */
    public  Map<String,String> buildGridDataGraphParam(String taskId,String dictCode,String flag,String type) throws Exception {

        LegendVo legendVo= new LegendVo();
        return getCommonDataMapParamData(taskId,dictCode,legendVo,flag,type);
    }
    /**
     * 测试用
     * 构造生产图例的参数对象
     * @param
     */
//    @Override
//    public void buildGraphParam(String taskId){
//
//        LegendVo legendVo= new LegendVo();
//        String dictCode="czqtjglxgw";
//        dictCode="czghjggw";
//        getCommonDataMapParamData(taskId,dictCode,legendVo,"");
//    }

    @Override
    public MapTemplate getMapTemplateData(String dictCode,String flag) {
        String sql = "select * from sys_map_tempate where dict_code = ? and flag=?";
        MapTemplate mapTemplate = null;
        try{
            mapTemplate = jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<>(MapTemplate.class),dictCode,flag);
        }catch (Exception e){
            e.printStackTrace();
        }
        return mapTemplate;
    }


    //根据经纬度范围获取level值
    public int getLevel(double leftBottom_X,double leftBottom_Y,double rightTop_X,double rightTop_Y,String formatType) {
        int level = 4;//默认级别4
        double minLon = leftBottom_X;
        double minLat = leftBottom_Y;
        double maxLon = rightTop_X;
        double maxLat = rightTop_Y;
        //获取最大差值
        double diffLon = maxLon - minLon;
        double diffLat = maxLat - minLat;
        double diffMax = diffLon;
        if(diffLon < diffLat){
            diffMax = diffLat;
        }
//        int diff = Math.round(diffMax);
//        long round = Math.round(diffMax);
        //1-18缩放级别zoom
        /*int[] levelArr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18};
        Double[] diffArr = {360.0,180.0,90.0,45.0,22.0,11.0,5.0,2.5,1.25, 0.6,0.3,0.15,0.07,0.03,0.015,0.007,0.0003,0.00015};
        for (int i = 0; i < diffArr.length; i++) {
            if (diffMax - diffArr[i] >= 0) {
                level = levelArr[i];
                break;
            }
        }*/
        int width,height;
        if(formatType.equals("横版")){
            width = 1510;
            height = 1020;
        }else if(formatType.equals("竖版")){//竖版
            width = 1150;
            height = 1230;
        }else{//横版带简介
            width = 1160;
            height = 1010;
        }
        //根据区域范围计算zoom级别，width、height是以像素为单位的地图布局大小
        level = getBoundsZoomLevel(leftBottom_X,leftBottom_Y,rightTop_X,rightTop_Y,width, height);

        return level;
    }

    final static int GLOBE_WIDTH = 256;
    final static int ZOOM_MAX = 18;
    //根据区域范围计算zoom级别，width、height是以像素为单位的地图布局大小
    public static int getBoundsZoomLevel(double leftBottom_X,double leftBottom_Y,double rightTop_X,double rightTop_Y,
                                         int width, int height) {
        double latFraction = (latRad(rightTop_Y) - latRad(leftBottom_Y)) / Math.PI;
        double lngDiff = rightTop_X - leftBottom_X;
        double lngFraction = ((lngDiff < 0) ? (lngDiff + 360) : lngDiff) / 360;
        double latZoom = zoom(height, GLOBE_WIDTH, latFraction);
        double lngZoom = zoom(width, GLOBE_WIDTH, lngFraction);
        double zoom = Math.min(Math.min(latZoom, lngZoom),ZOOM_MAX);
        return (int)(zoom);
    }
    private static double latRad(double lat) {
        double sin = Math.sin(lat * Math.PI / 180);
        double radX2 = Math.log((1 + sin) / (1 - sin)) / 2;
        return Math.max(Math.min(radX2, Math.PI), -Math.PI) / 2;
    }
    private static double zoom(double mapPx, double worldPx, double fraction) {
        final double LN2 = .693147180559945309417;
        return (Math.log(mapPx / worldPx / fraction) / LN2);
    }


    //设置打印出图请求体
    private RequestVO getRequestVO(LegendVo legendVo, Map<String, Double> hashMap,String taskId,String type) throws Exception {
        Map<String, Object> taskObjById = null;
        if("5".equals(type) || "6".equals(type)){
            taskObjById = getSmxTaskObjById(taskId);
        }else{
            taskObjById = getTaskObjById(taskId);
        }
        String geom = publicOperateService.getDistrictGeom(taskObjById);
        RequestVO requestVO = new RequestVO();
        LayoutOptions layoutOptions = new LayoutOptions();
        MapTemplate mapTemplate = legendVo.getMapTemplate();
//        layoutOptions.setTemplateName("LayoutTemplatetest");
//        String templateName = "Administrative_Active_Fault-h0926";//有备注参数summaryText
//        String templateName = "Administrative_Active_Fault-hf0926";
        String templateName = "Administrative_Active_Fault-hf1012";
        String format = mapTemplate.getFormat();//版式  0横板  1竖版  2无 3横版带简介
        if(format.equals("0")){//0横板
//            templateName = "Administrative_Active_Fault-hf0926";//测试横版
            templateName = "Administrative_Active_Fault-hf1012";//测试横版
        }else if(format.equals("1")){//1竖版
//            templateName = "Administrative_Active_Fault-v0926";//测试竖版
            templateName = "Administrative_Active_Fault-v1012";//测试竖版
        }else if(format.equals("2")){//2无
//            templateName = "Administrative_Active_Fault-hf0926";//测试横版
            templateName = "Administrative_Active_Fault-hf1012";//测试横版
        }else if(format.equals("3")){//3横版带简介
//            templateName = "Administrative_Active_Fault-h0926";//测试横版带简介
            templateName = "Administrative_Active_Fault-h1012";//测试横版带简介
        }
        layoutOptions.setTemplateName(templateName);//test
//        layoutOptions.setTitle(mapTemplate.getDictType());
        String title = legendVo.getTitle();
        if(PlatformObjectUtils.isEmpty(title)){
            title="标题";
        }
        layoutOptions.setTitle(title);//标题
        layoutOptions.setAuthor("制图单位："+legendVo.getUnit());//制图单位
        String date = DateUtil.format(new Date(), "yyyy年MM月dd日");
        layoutOptions.setTime("制图时间:"+date);//制图时间
        if("RealAnalyse_Kangzhen".equals(mapTemplate.getDictCode())){//基于遥感影像的XX震中影响场范围内房屋抗震能力初判图
            layoutOptions.setSummaryText(legendVo.getSummaryText());
        }
        ScaleBarOptions scaleBarOptions = new ScaleBarOptions("","BAR",5,"METER");
        layoutOptions.setScaleBarOptions(scaleBarOptions);
//        NorthArrowOptions northArrowOptions = new NorthArrowOptions("file://NorthArrow.svg");
        NorthArrowOptions northArrowOptions = new NorthArrowOptions("file://ARROW_RIGHT_FILL_WITH_COLOR.svg");
        layoutOptions.setNorthArrowOptions(northArrowOptions);
//        MapGridOptions mapGridOptions = new MapGridOptions();//经纬度网格边框
//        mapGridOptions.setOriginX(-180);
//        mapGridOptions.setOriginY(-90);
//        mapGridOptions.setCellWidth(10);
//        mapGridOptions.setCellHeight(10);
//        mapGridOptions.setMarkType("DMS");
        //获取经纬网参数
        MapGridOptions mapGridOptions = supergraphService.getMapGridOptions(hashMap.get("leftX"), hashMap.get("leftY"), hashMap.get("rightX"), hashMap.get("rightY"));
        layoutOptions.setMapGridOptions(mapGridOptions);
        LegendOption legendOption = new LegendOption();
        legendOption.setTitle("图 例");
        String dictCode = mapTemplate.getDictCode();//出图类型字典code
        //根据dictCode、任务ID获取临时图层URL的Map
        //Map<String,String> tempLayerUrlMap = getTempLayerUrlMapByDictCode(dictCode,legendVo);
        if("catalog_xzqht".equals(dictCode)){
            System.out.println("111");
        }
        Map<String,String> tempLayerUrlMap = getTempLayerUrlMapByDictCode1(dictCode,legendVo,mapTemplate,taskObjById,geom);
        //图例
        List<Layerr> layerrs = getLayerrs(dictCode,legendVo,tempLayerUrlMap,taskObjById,geom);
        legendOption.setLayers(layerrs);
        layoutOptions.setLegendOptions(legendOption);
        requestVO.setLayoutOptions(layoutOptions);
        ExportOptions exportOptions = new ExportOptions("png", 120.0);
        requestVO.setExportOptions(exportOptions);
        Content content = new Content();
        content.setType("WEBMAP");
        com.css.fxfzfxqh.modules.reportmanagement.legend.Value value = new com.css.fxfzfxqh.modules.reportmanagement.legend.Value();
        LeftAndright leftBottom = new LeftAndright(hashMap.get("leftX"), hashMap.get("leftY"));
        LeftAndright rightTop = new LeftAndright(hashMap.get("rightX"), hashMap.get("rightY"));
        Extent extent = new Extent(leftBottom, rightTop);
        value.setExtent(extent);
        value.setMaxScale("1:2130.3378410848");
        value.setLevel(hashMap.get("level"));
        if(format.equals("3")) {//3横版带简介
            int level = getLevel(hashMap.get("leftX"), hashMap.get("leftY"), hashMap.get("rightX"), hashMap.get("rightY"),"横版带简介");
            value.setLevel(Double.valueOf(level));
        }
//        value.setLevel(11.0);
        LeftAndright center = new LeftAndright(hashMap.get("centerX"), hashMap.get("centerY"));
        value.setCenter(center);
//        BaseLayer baseLayer = new BaseLayer("TILE", "China", "http://10.13.155.192:8090/iserver/services/map-fxfzypg/rest/maps/data_faultage@fxfzypg");
//        value.setBaseLayer(baseLayer);
        //图层
        List<Layer> layers = getLayers(dictCode,legendVo,tempLayerUrlMap,taskObjById,geom);
        value.setLayers(layers);
        value.setDescription("");
        value.setProjection("EPSG:4490");
        value.setMinScale("1:591658710.909131");
        value.setTitle("China");
        value.setVersion("2.3.0");
        content.setValue(value);
        requestVO.setContent(content);
        return requestVO;
    }

    private List<Layer> getLayers(String dictCode,LegendVo legendVo,Map<String,String> tempLayerUrlMap, Map<String, Object> taskObjById,String geom) {
        List<Layer> layers = new ArrayList<>();
        String taskId = taskObjById.get("id").toString();
        if(!dictCode.contains("smx_expire")){
            MapTemplate mapTemplate = legendVo.getMapTemplate();
            String serverUrl1 = mapTemplate.getServerUrl();
            String url_1 = "";
            if("catalog_yxc".equals(dictCode)){
                //影响场数据
                StringBuffer sb=new StringBuffer();
                sb.append(" version_code='").append(taskObjById.get("influence_field_version")).append("' and del_flag='0'");
                url_1 = getSqlTempLayer(mapTemplate.getServerIpPort()+serverUrl1, sb.toString(),true);
            }else if("catalog_jjfbt".equals(dictCode)){
                //经济分布图
                String version = (String)taskObjById.get("gdp_version");
                StringBuffer sb=new StringBuffer();
                sb.append(" data_version='").append(version).append("' and del_flag='0' and st_intersects(geom, st_geomfromtext('").append(geom).append("',4490))");
                url_1 =  getSqlTempLayer(mapTemplate.getServerIpPort()+mapTemplate.getServerUrl(), sb.toString(),true);
            }else if("catalog_rygbt".equals(dictCode)){
                //人口分布图
                String version = (String)taskObjById.get("popluation_version");
                StringBuffer sb=new StringBuffer();
                sb.append(" data_version='").append(version).append("' and del_flag='0' and st_intersects(geom, st_geomfromtext('").append(geom).append("',4490))");
                url_1 = getSqlTempLayer(mapTemplate.getServerIpPort()+mapTemplate.getServerUrl(), sb.toString(),true);
            }else{
                url_1 = new StringBuilder().append(mapTemplate.getServerIpPort()).append(serverUrl1).toString();
            }
            String layerName =url_1.substring( url_1.lastIndexOf("/")+1).split("@")[0];
            if(tempLayerUrlMap!=null&&!tempLayerUrlMap.isEmpty()){
                if("catalog_xzqht".equals(dictCode)){
                    url_1=tempLayerUrlMap.get("district");
                }else{
                    url_1=tempLayerUrlMap.get(dictCode);
                }
            }
            Layer layer1 = new Layer("TILE",true,layerName,url_1);
            layers.add(layer1);
            //if("catalog_xzqht".equals(dictCode)){
                String newServerUrl = tempLayerUrlMap.get("district");
                String newLayerName =newServerUrl.substring( newServerUrl.lastIndexOf("/")+1).split("@")[0];
                Layer newLayer1 = new Layer("TILE",true,newLayerName,newServerUrl);
                layers.add(newLayer1);
            //}
        }else{
            tempLayerUrlMap.forEach((k,v)->{
//                String layerName =v.substring( v.lastIndexOf("/")+1).split("@")[0];
                String tempName =v.split("@")[0];
                String layerName =tempName.substring( tempName.lastIndexOf("/")+1);
                Layer layer1 = new Layer("TILE",true,layerName,v);
                layers.add(layer1);
            });
            //生命线报告的失效等级图需要将对应的几个基础数据的评估对象合在一起，评估对象有点数据和线数据，
            // 其中数据表中只存了电地址，需要手动的变更和加上线地址（除了通信系统外，其他系统都存在线数据）
            MapTemplate mapTemplate = legendVo.getMapTemplate();
            StringBuffer sb=new StringBuffer();
            sb.append(" task_id='").append(taskId).append("'");
            String dataSource = dictCode.split("_")[2];
            //烈度
            String intensity = dictCode.split("_")[3];
            if("gsxt".equals(dataSource)){
                //供水系统-地下管网
                sb.append("  and type ='1'");
            }else if("gqxt".equals(dataSource)){
                //供气系统-供气管网
                sb.append("  and  type='15'");
            }else if("gdxt".equals(dataSource)){
                //供电系统-电缆线路
                sb.append("  and type='8' ");
            }else if("jtxt".equals(dataSource)){
                //交通系统-道路和桥梁
                sb.append("  and (type='4' or type='5' )");
            }
            String columnName = "";
            if(!"yxc".equals(intensity)){
                columnName = intensityMap().get(intensity);
            }else{
                columnName = "disaster_rate_state_correction";
            }
            sb.append("  and ").append(columnName).append(" in ('基本完好','轻微破坏','中等破坏','严重破坏','倒塌')");
            //手动变更超图地址
            String serverUrl = mapTemplate.getServerUrl();
            int index = serverUrl.lastIndexOf("_");
            String prefix = serverUrl.substring(0,index)+"_line_";
            String suffix = serverUrl.substring(index+1);
            serverUrl = prefix+suffix;
            String tempLayerUrl = getSqlTempLayer(mapTemplate.getServerIpPort()+serverUrl, sb.toString(),true);
            String tempName =tempLayerUrl.split("@")[0];
            String layerName =tempName.substring( tempName.lastIndexOf("/")+1);
            //String layerName =tempLayerUrl.substring( tempLayerUrl.lastIndexOf("/")+1).split("@")[0];
            Layer layer1 = new Layer("TILE",true,layerName,tempLayerUrl);
            layers.add(layer1);
        }
        //if(dictCode.endsWith("jggw") || dictCode.startsWith("jjph_") || dictCode.startsWith("rysw_") || dictCode.startsWith("economic_") ){
            //表示是 图2-1~图2-13各类型房屋公里网格分布图，需要再加上一个行政区划图，其他的不需要
        String url_2 = iServerHttp+"/iserver/services/map-fxfzypg/rest/maps/district_boundary_china@fxfzypg";
        String newLayerName = "district_boundary_china";
        Layer newLayer1 = new Layer("TILE",true,newLayerName,url_2);
        layers.add(newLayer1);
        //}
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String url = configGroup.getProperty("supergraphRestTemplateUrl");
        return layers;
    }

    //获取图层图例名称数组（除文字标签）
    private List<String> getLegendLayerNameList(String layerName,String layerUrl){
        //如果没有文字标签，则返回空数组代表显示全部图例
        List<String> legendLayerNameList = new ArrayList<>();
        JSONArray jsonArray = getLayersRJson(layerUrl);
        boolean bool = false;
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONArray layers = jsonArray.getJSONObject(i).getJSONObject("subLayers").getJSONArray("layers");
            for(int j=0;j<layers.size();j++){
                JSONObject layer = layers.getJSONObject(j);
                //获取图层过滤条件
                String name = layer.getString("name");
                name = name.replace("#",".");
                String legendLayerName = name + "@@" + layerName;
                String ugcLayerType = layer.getString("ugcLayerType");
                if (ugcLayerType.equals("THEME")) {
                    if("LABEL".equals(layer.getJSONObject("theme").getString("type"))){
                        //文字标签
                        bool = true;
                    }else{
                        legendLayerNameList.add(legendLayerName);
                    }
                }else{
                    legendLayerNameList.add(legendLayerName);
                }
            }
        }
        if(bool==false){//无文字标签显示全部图例
            legendLayerNameList = new ArrayList<>();
        }

        return legendLayerNameList;
    }
    private List<Layerr> getLayerrs(String dictCode,LegendVo legendVo,Map<String,String> tempLayerUrlMap,Map<String, Object> taskObjById,String geom) {
//        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
//        String url = configGroup.getProperty("supergraphRestTemplateUrl");
        String taskId = taskObjById.get("id").toString();
        List<Layerr> layerrList = new ArrayList<>();
        //不是生命线的破坏等级图和失效等级图
//        if(!"5".equals(type) && !"6".equals(type) && !dictCode.contains("smx_expire")){
        if(!dictCode.contains("smx_expire")){
            MapTemplate mapTemplate = legendVo.getMapTemplate();
            String serverUrl1 = mapTemplate.getServerUrl();
            String serverUrl = "";
            if("catalog_yxc".equals(dictCode)){
                //影响场数据
                StringBuffer sb=new StringBuffer();
                sb.append(" version_code='").append(taskObjById.get("influence_field_version")).append("' and del_flag='0'");
                serverUrl = getSqlTempLayer(mapTemplate.getServerIpPort()+serverUrl1, sb.toString(),true);
            } else if("catalog_jjfbt".equals(dictCode)){
                //经济分布图
                String version = (String)taskObjById.get("gdp_version");
                StringBuffer sb=new StringBuffer();
                sb.append(" data_version='").append(version).append("' and del_flag='0' and st_intersects(geom, st_geomfromtext('").append(geom).append("',4490))");
                serverUrl =  getSqlTempLayer(mapTemplate.getServerIpPort()+mapTemplate.getServerUrl(), sb.toString(),true);
            }else if("catalog_rygbt".equals(dictCode)){
                //人口分布图
                String version = (String)taskObjById.get("popluation_version");
                StringBuffer sb=new StringBuffer();
                sb.append(" data_version='").append(version).append("' and del_flag='0' and st_intersects(geom, st_geomfromtext('").append(geom).append("',4490))");
                serverUrl = getSqlTempLayer(mapTemplate.getServerIpPort()+mapTemplate.getServerUrl(), sb.toString(),true);
            }else{
                serverUrl = new StringBuilder().append( mapTemplate.getServerIpPort()).append(serverUrl1).toString();
            }
            System.out.println("==========dictCode:"+dictCode+"源地址=============="+serverUrl);
            if(tempLayerUrlMap!=null&&!tempLayerUrlMap.isEmpty()){
                if("catalog_xzqht".equals(dictCode)){
                    serverUrl=tempLayerUrlMap.get("district");
                }else{
                    serverUrl=tempLayerUrlMap.get(dictCode);
                }
                System.out.println("==========dictCode:"+dictCode+"临时图层地址=============="+serverUrl);
            }
            int index = serverUrl1.lastIndexOf("/")+ 1;
            List<String> legendLayerNameList = getLegendLayerNameList(serverUrl1.substring(index), serverUrl);
            Layerr layerr = new Layerr(serverUrl,legendLayerNameList);
            layerrList.add(layerr);

            String newServerUrl = tempLayerUrlMap.get("district");
            legendLayerNameList = getLegendLayerNameList("fxqh_assess_toponym@fxfzfxqh", newServerUrl);
            Layerr newLayerr = new Layerr(newServerUrl,legendLayerNameList);
            layerrList.add(newLayerr);

        }else{
            tempLayerUrlMap.forEach((k,v)->{
                int index = v.lastIndexOf("/")+ 1;
                List<String> legendLayerNameList = getLegendLayerNameList(v.substring(index), v);
                Layerr layerr = new Layerr(v,legendLayerNameList);
                layerrList.add(layerr);
            });
            //生命线报告的失效等级图需要将对应的几个基础数据的评估对象合在一起，评估对象有点数据和线数据，
            // 其中数据表中只存了电地址，需要手动的变更和加上线地址（除了通信系统外，其他系统都存在线数据）
            MapTemplate mapTemplate = legendVo.getMapTemplate();
            StringBuffer sb=new StringBuffer();
            sb.append(" task_id='").append(taskId).append("'");
            String dataSource = dictCode.split("_")[2];
            //烈度
            String intensity = dictCode.split("_")[3];
            if("gsxt".equals(dataSource)){
                //供水系统-地下管网
                sb.append("  and type ='1'");
            }else if("gqxt".equals(dataSource)){
                //供气系统-供气管网
                sb.append("  and  type='15'");
            }else if("gdxt".equals(dataSource)){
                //供电系统-电缆线路
                sb.append("  and type='8' ");
            }else if("jtxt".equals(dataSource)){
                //交通系统-道路和桥梁
                sb.append("  and (type='4' or type='5' )");
            }
            String columnName = "";
            if(!"yxc".equals(intensity)){
                columnName = intensityMap().get(intensity);
            }else{
                columnName = "disaster_rate_state_correction";
            }
            sb.append("  and ").append(columnName).append(" in ('基本完好','轻微破坏','中等破坏','严重破坏','倒塌')");
            //手动变更超图地址
            String serverUrl = mapTemplate.getServerUrl();
            int index = serverUrl.lastIndexOf("_");
            String prefix = serverUrl.substring(0,index)+"_line_";
            String suffix = serverUrl.substring(index+1);
            serverUrl = prefix+suffix;
            String tempLayerUrl = getSqlTempLayer(mapTemplate.getServerIpPort()+serverUrl, sb.toString(),true);
            index = serverUrl.lastIndexOf("/")+ 1;
            List<String> legendLayerNameList = getLegendLayerNameList(serverUrl.substring(index), tempLayerUrl);
            Layerr layerr = new Layerr(tempLayerUrl,legendLayerNameList);
            layerrList.add(layerr);
        }

        //if(!"5".equals(type) && !"6".equals(type) ){
        String url_2 = iServerHttp+"/iserver/services/map-fxfzypg/rest/maps/district_boundary_china@fxfzypg";
        List<String> legendLayerNameList = getLegendLayerNameList("district_boundary_china@fxfzypg", url_2);
        Layerr newLayer1 = new Layerr(url_2,legendLayerNameList);
        layerrList.add(newLayer1);
        return layerrList;
    }

    //根据dictCode、任务ID获取临时图层URL的Map
    public Map<String,String> getTempLayerUrlMapByDictCode(String dictCode,LegendVo legendVo){
        Map<String,String> tempLayerUrlMap = new HashMap<>();
        String dzIntensity = legendVo.getDzIntensity();//烈度6-10：建筑物综合抗震能力评价图（区县、乡镇、格网）每种类型按不同烈度保存多张图
        if ("Seismic_Capacity_County".equals(dictCode)) {//建筑物综合抗震能力评价图(区县)
            String tempLayerUrl = getTempLayerUrlByDataType("seismic_capacity_distribution_0_"+dzIntensity,legendVo);
            tempLayerUrlMap.put("seismic_capacity_distribution_0_"+dzIntensity,tempLayerUrl);
        }else if ("Seismic_Capacity_Town".equals(dictCode)) {//建筑物综合抗震能力评价图(乡镇)
            String tempLayerUrl = getTempLayerUrlByDataType("seismic_capacity_distribution_1_"+dzIntensity,legendVo);
            tempLayerUrlMap.put("seismic_capacity_distribution_1_"+dzIntensity,tempLayerUrl);
        }else if ("Seismic_Capacity_Grid".equals(dictCode)) {//建筑物综合抗震能力评价图(格网)
            String tempLayerUrl = getTempLayerUrlByDataType("seismic_capacity_distribution_2_"+dzIntensity,legendVo);
            tempLayerUrlMap.put("seismic_capacity_distribution_2_"+dzIntensity,tempLayerUrl);
        }else if ("Scenario_Earthquake".equals(dictCode)) {//设置地震点分布图
            String tempLayerUrl = getTempLayerUrlByDataType("setting_seismic_point",legendVo);
            tempLayerUrlMap.put("setting_seismic_point",tempLayerUrl);
            String tempLayerUrl2 = getTempLayerUrlByDataType("ypg_preassess_task",legendVo);
            tempLayerUrlMap.put("ypg_preassess_task",tempLayerUrl2);
        }else if ("Research_Points".equals(dictCode)) {//调研点分布图
            String tempLayerUrl = getTempLayerUrlByDataType("ypg_sampling_survey_new",legendVo);
            tempLayerUrlMap.put("ypg_sampling_survey_new",tempLayerUrl);
        }else if ("Geologic_Hazard_Risk".equals(dictCode)) {//遭遇烈度XX度地震地质灾害风险分布图
            String tempLayerUrl = getTempLayerUrlByDataType("ypg_result_road_new",legendVo);
            tempLayerUrlMap.put("ypg_result_road_new",tempLayerUrl);
            String tempLayerUrl2 = getTempLayerUrlByDataType("ypg_result_slope",legendVo);
            tempLayerUrlMap.put("ypg_result_slope",tempLayerUrl2);
        }else if ("Traffic_Damage".equals(dictCode)) {//交通遭遇烈度XX度时交通受损情况分布图
            String tempLayerUrl = getTempLayerUrlByDataType("ypg_result_road_new",legendVo);
            tempLayerUrlMap.put("ypg_result_road_new",tempLayerUrl);
            String tempLayerUrl2 = getTempLayerUrlByDataType("ypg_result_slope",legendVo);
            tempLayerUrlMap.put("ypg_result_slope",tempLayerUrl2);
        }else if (dictCode.contains("RealAnalyse_")) {//震后辅助决策分析结果打印出图
            //基于遥感影像的XX震中影响场范围内房屋抗震能力初判图(RealAnalyse_Kangzhen)
            //建筑物公里格网分布对比图(RealAnalyse_Building)
            //人口公里格网分布对比图(RealAnalyse_Population)
            //经济格网分布对比图(RealAnalyse_GDP)
            //获取临时图层--实际地震烈度影响场
            String tempLayerUrl = tempLayerUrlMap.get("real_seismic_influenceflied");
            if(PlatformObjectUtils.isEmpty(tempLayerUrl)){
                tempLayerUrl = getTempLayerUrlByDataType("real_seismic_influenceflied",legendVo);
                tempLayerUrlMap.put("real_seismic_influenceflied",tempLayerUrl);
            }
            //获取临时图层--震中
            String tempLayerUrl2 = tempLayerUrlMap.get("real_earthquake_info");
            if(PlatformObjectUtils.isEmpty(tempLayerUrl2)){
                tempLayerUrl2 = getTempLayerUrlByDataType("real_earthquake_info",legendVo);
                tempLayerUrlMap.put("real_earthquake_info",tempLayerUrl2);
            }
            //获取临时图层--设定地震烈度影响场
            String tempLayerUrl3 = tempLayerUrlMap.get("setting_seismic_influenceflied");
            if(PlatformObjectUtils.isEmpty(tempLayerUrl3)){
                tempLayerUrl3 = getTempLayerUrlByDataType("setting_seismic_influenceflied",legendVo);
                tempLayerUrlMap.put("setting_seismic_influenceflied",tempLayerUrl3);
            }
            //获取临时图层--设定地震震中
            String tempLayerUrl4 = tempLayerUrlMap.get("设定地震震中");
            if(PlatformObjectUtils.isEmpty(tempLayerUrl4)){
                tempLayerUrl4 = getTempLayerUrlByDataType("设定地震震中",legendVo);
                tempLayerUrlMap.put("设定地震震中",tempLayerUrl4);
            }
            //获取临时图层--真实地震震中
            String tempLayerUrl5 = tempLayerUrlMap.get("真实地震震中");
            if(PlatformObjectUtils.isEmpty(tempLayerUrl5)){
                tempLayerUrl5 = getTempLayerUrlByDataType("真实地震震中",legendVo);
                tempLayerUrlMap.put("真实地震震中",tempLayerUrl5);
            }
        }
        return tempLayerUrlMap;
    }

    private Map<String,String> intensityMap(){
        Map<String,String> map = new HashMap<>();
        map.put("1","disaster_rate6_state_correction");
        map.put("2","disaster_rate7_state_correction");
        map.put("3","disaster_rate8_state_correction");
        map.put("4","disaster_rate9_state_correction");
        map.put("5","disaster_rate10_state_correction");
        return map;
    }

    public Map<String,String> getTempLayerUrlMapByDictCode1(String dictCode,LegendVo legendVo,MapTemplate mapTemplate,Map<String, Object> taskObjById,String geom) throws Exception {
        Map<String,String> tempLayerUrlMap = new HashMap<>();
        String taskId = (String) taskObjById.get("id");
        String templateFlag = mapTemplate.getFlag();

        StringBuffer buffer=new StringBuffer();
        buffer.append(" assess_id='").append(taskId).append("'");
        String newServerUrl = getSqlTempLayer(mapTemplate.getServerIpPort()+"map-fxfzfxqh/rest/maps/fxqh_assess_toponym@fxfzfxqh", buffer.toString(),true);
        tempLayerUrlMap.put("district",newServerUrl);

        if (dictCode.startsWith("rysw_")) {//人员伤亡
            String flag = dictCode.substring(dictCode.lastIndexOf("_")+1, dictCode.length());
            StringBuffer sb=new StringBuffer();
            sb.append("assess_id='"+taskId+"'");
            if("1".equals(templateFlag)){
                String intensity=flag;
                switch (flag){//
                    case "1": intensity="Ⅵ";break;
                    case "2": intensity="Ⅶ";break;
                    case "3": intensity="Ⅷ";break;
                    case "4": intensity="Ⅸ";break;
                    case "5": intensity="Ⅹ";break;
                }
                sb.append(" and flag='0' and intensity='"+intensity+"'");
            }
            if("2".equals(templateFlag)){
                sb.append(" and flag='1' and condition='"+flag+"'");
            }
            if("3".equals(templateFlag)){
                String influenceVersion = taskObjById.get("influence_field_version").toString();
                sb.append(" and flag='2' and version='"+influenceVersion+"'");
            }
            String tempLayerUrl = getSqlTempLayer(mapTemplate.getServerIpPort()+mapTemplate.getServerUrl(), sb.toString(),true);
            tempLayerUrlMap.put(dictCode,tempLayerUrl);
        }else if (dictCode.contains("jjph_")){
            //破坏程度
            String destory = "";

            StringBuffer sb=new StringBuffer();
            //条件
            String condition = "";
            if("1".equals(templateFlag) || "2".equals(templateFlag)){
                //1是烈度 ld1-ld5 ，2是四个概率水准 pgcd1-pgcd5
                condition = dictCode.split("_")[1];
                destory = dictCode.split("_")[2];
                legendVo.setCondition(condition);
                legendVo.setDestory(destory);
                sb.append("assess_id='").append(taskId).append("'").append("  and condition='").append(condition).append("' and damage_degree='").append(destory).append("'");
                String tempLayerUrl = getSqlTempLayer(mapTemplate.getServerIpPort()+mapTemplate.getServerUrl(), sb.toString(),true);
                tempLayerUrlMap.put(dictCode,tempLayerUrl);
            }else if("3".equals(templateFlag)){
                //影响场版本
                //获取影响场版本
                Object influenceVersion = taskObjById.get("influence_field_version");
                if(PlatformObjectUtils.isNotEmpty(influenceVersion)){
                    condition = (String) influenceVersion;
                }
                destory = dictCode.split("_")[1];
                legendVo.setVersion(condition);
                legendVo.setDestory(destory);
                sb.append("assess_id='").append(taskId).append("'").append("  and version='").append(condition).append("' and damage_degree='").append(destory).append("'");
                String tempLayerUrl = getSqlTempLayer(mapTemplate.getServerIpPort()+mapTemplate.getServerUrl(), sb.toString(),true);
                tempLayerUrlMap.put(dictCode,tempLayerUrl);
            }


        }else if (dictCode.startsWith("dzb_")) {//单指标
            String flag = dictCode.substring(dictCode.lastIndexOf("_")+1, dictCode.length());
            legendVo.setDzIntensity(flag);
            String[] split = dictCode.split("_");
            String estimate_obj="0"; //默认结构破坏
            switch (split[1]){
                case "jgph": estimate_obj="0";break;
                case "rysw": estimate_obj="1";break;
                case "jjss": estimate_obj="2";break;
            }
            StringBuffer sb=new StringBuffer();
            sb.append("task_id='"+taskId+"'");
            if("3".equals(templateFlag)){
                String influenceVersion = taskObjById.get("influence_field_version").toString();
                flag=influenceVersion;
            }
            sb.append(" and estimate_obj='"+estimate_obj+"' and condition='"+flag+"'");

            String tempLayerUrl = getSqlTempLayer(mapTemplate.getServerIpPort()+mapTemplate.getServerUrl(), sb.toString(),true);
            tempLayerUrlMap.put(dictCode,tempLayerUrl);
        }else if (dictCode.startsWith("zhzb_")) {//综合单指标
            String flag = dictCode.substring(dictCode.lastIndexOf("_")+1, dictCode.length());
            legendVo.setDzIntensity(flag);
            StringBuffer sb=new StringBuffer();
            sb.append("task_id='"+taskId+"'");
            if("3".equals(templateFlag)){
                //String influenceVersion = taskObjById.get("influence_field_version").toString();
                flag = taskObjById.get("influence_field_version").toString();
            }
            sb.append(" and type='"+flag+"'");

            String tempLayerUrl = getSqlTempLayer(mapTemplate.getServerIpPort()+mapTemplate.getServerUrl(), sb.toString(),true);
            tempLayerUrlMap.put(dictCode,tempLayerUrl);
        }else if (dictCode.startsWith("economic_")) {//地震直接经济损失评估
            Map<String,Object> taskObj = getTaskObjById(taskId);
            String flag = dictCode.substring(dictCode.lastIndexOf("_")+1, dictCode.length());

            StringBuffer sb=new StringBuffer();
            sb.append("assess_id='"+taskId+"'");
            if("3".equals(templateFlag)){
                String influenceVersion = taskObj.get("influence_field_version").toString();
                flag=influenceVersion;
            }
            legendVo.setDzIntensity(flag);
            sb.append("  and condition='"+flag+"'");

            String tempLayerUrl = getSqlTempLayer(mapTemplate.getServerIpPort()+mapTemplate.getServerUrl(), sb.toString(),true);
            tempLayerUrlMap.put(dictCode,tempLayerUrl);
        }else if (dictCode.startsWith("fzgv_")) {//发生概率逻辑
            String flag = dictCode.substring(dictCode.lastIndexOf("_")+1, dictCode.length());
            if("dzb".equals(flag)){
                legendVo.setDzIntensity(flag);
                String[] split = dictCode.split("_");
                String estimate_obj="0"; //默认结构破坏
                switch (split[1]){
                    case "jgph": estimate_obj="0";break;
                    case "rysw": estimate_obj="1";break;
                    case "jjss": estimate_obj="2";break;
                }
                StringBuffer sb=new StringBuffer();
                sb.append("task_id='"+taskId+"'");
                sb.append(" and estimate_obj='"+estimate_obj+"' and condition='"+legendVo.getYear()+"'");

                String tempLayerUrl = getSqlTempLayer(mapTemplate.getServerIpPort()+mapTemplate.getServerUrl(), sb.toString(),true);
                tempLayerUrlMap.put(dictCode,tempLayerUrl);
            }else if("zhzb".equals(flag)){
                StringBuffer sb=new StringBuffer();
                sb.append("task_id='"+taskId+"'");
                sb.append(" and type='"+legendVo.getYear()+"'");

                String tempLayerUrl = getSqlTempLayer(mapTemplate.getServerIpPort()+mapTemplate.getServerUrl(), sb.toString(),true);
                tempLayerUrlMap.put(dictCode,tempLayerUrl);
            }else if("rysw".equals(flag)){
                String[] split = dictCode.split("_");
                String timeFlag=split[2];//时间段(白天晚上) 晚上0，白天1
                if("0".equals(timeFlag)){
                    timeFlag = "sjd2";
                }else{
                    timeFlag = "sjd1";
                }
                String casualtiesFlag=split[1];//人员伤亡(死亡2重伤1)
                if("1".equals(casualtiesFlag)){
                    casualtiesFlag = "rysw1";
                }else{
                    casualtiesFlag = "rysw2";
                }
                StringBuffer sb=new StringBuffer();
                sb.append(" assess_id='"+taskId+"'");
                sb.append(" and time='"+timeFlag+"'");
                sb.append(" and casualties='"+casualtiesFlag+"'");
                //sb.append(" and years='"+legendVo.getYear()+"'");
                String tempLayerUrl = getSqlTempLayer(mapTemplate.getServerIpPort()+mapTemplate.getServerUrl(), sb.toString(),true);
                tempLayerUrlMap.put(dictCode,tempLayerUrl);
            }else if("economic".equals(flag)){
                StringBuffer sb=new StringBuffer();
                sb.append("assess_id='"+taskId+"'");
                //sb.append(" and years='"+legendVo.getYear()+"'");
                String tempLayerUrl = getSqlTempLayer(mapTemplate.getServerIpPort()+mapTemplate.getServerUrl(), sb.toString(),true);
                tempLayerUrlMap.put(dictCode,tempLayerUrl);
            }else if("jjph".equals(flag)){
                String destory = dictCode.split("_")[1];
                StringBuffer sb=new StringBuffer();
//                sb.append("assess_id='").append(taskId).append("'").append("  and years='").append(legendVo.getYear()).append("' and damage_degree='").append(destory).append("'");
                sb.append("assess_id='").append(taskId).append("'").append("' and damage_degree='").append(destory).append("'");
                String tempLayerUrl = getSqlTempLayer(mapTemplate.getServerIpPort()+mapTemplate.getServerUrl(), sb.toString(),true);
                tempLayerUrlMap.put(dictCode,tempLayerUrl);
            }
        }else if(dictCode.startsWith("dzwxx_")){
            String fourProbabilisticVersions = taskObjById.get("four_probabilistic_versions").toString();
            StringBuffer sb=new StringBuffer();
            sb.append(" assess_id='"+taskId+"'");
            sb.append("  and data_version='"+fourProbabilisticVersions+"'");
            String tempLayerUrl = getSqlTempLayer(mapTemplate.getServerIpPort()+mapTemplate.getServerUrl(), sb.toString(),true);
            tempLayerUrlMap.put(dictCode,tempLayerUrl);
        }else if(dictCode.contains("smx_destroy")){
            //生命线 破坏等级图
            StringBuffer sb=new StringBuffer();
            sb.append(" task_id='").append(taskId).append("'");
            String catalogName = mapTemplate.getCatalogName();
            //类型
            String dataType = catalogName.split("_")[0];
            sb.append("  and type ='").append(dataType).append("'");
            //烈度
            String intensity = catalogName.split("_")[1];
            String columnName = "";
            if(!"yxc".equals(intensity)){
                columnName = intensityMap().get(intensity);
            }else{
                columnName = "disaster_rate_state_correction";
            }
            sb.append("  and "+columnName+" in ('基本完好','轻微破坏','中等破坏','严重破坏','倒塌')");
            String tempLayerUrl = getSqlTempLayer(mapTemplate.getServerIpPort()+mapTemplate.getServerUrl(), sb.toString(),true);
            tempLayerUrlMap.put(dictCode,tempLayerUrl);
        }else if(dictCode.contains("smx_expire")){
            //生命线 失效等级图
            StringBuffer sb=new StringBuffer();
            sb.append(" task_id='").append(taskId).append("'");
            String dataSource = dictCode.split("_")[2];
            //烈度
            String intensity = dictCode.split("_")[3];
            //1地下管网(线)，2水厂水池（点），3燃气储气罐（点） 4 桥梁(线数据、点数据) 5道路（线） 6变电站（点） 8电缆线路（线）
            // 9通信室内设备（点） 11 水厂泵房（点） 12 重要发电厂房（点） 13 通信基站（点） 14 燃气门站（点）
            if("gsxt".equals(dataSource)){
                //供水系统
                sb.append("  and (type='2' or type='11' )");
            }else if("gqxt".equals(dataSource)){
                //供气系统
                sb.append("  and (type='3' or type='14' )");
            }else if("gdxt".equals(dataSource)){
                //供电系统
                sb.append("  and (type='6' or type='12' )");
            }else if("jtxt".equals(dataSource)){
                //交通系统
                sb.append("  and type='4' ");
            }else if("txxt".equals(dataSource)){
                //通信系统
                sb.append("  and (type='9' or type='13' )");
            }
            String columnName = "";
            if(!"yxc".equals(intensity)){
                columnName = intensityMap().get(intensity);
            }else{
                columnName = "disaster_rate_state_correction";
            }
            sb.append("  and ").append(columnName).append(" in ('基本完好','轻微破坏','中等破坏','严重破坏','倒塌')");
            String tempLayerUrl = getSqlTempLayer(mapTemplate.getServerIpPort()+mapTemplate.getServerUrl(), sb.toString(),true);
            tempLayerUrlMap.put(dictCode,tempLayerUrl);
        }else if(dictCode.contains("catalog_sgcyglfbt")){
            //四个超越概率分布图  map-datacenter/rest/maps/jc_pga100_1@datacenter
            String version = (String)taskObjById.get("four_probabilistic_versions");
            StringBuffer sb=new StringBuffer();
            sb.append(" data_version='").append(version).append("' and del_flag='0' and st_intersects(geom, st_geomfromtext('").append(geom).append("',4490))");
            String url = mapTemplate.getServerUrl();
            if(taskObjById.get("ld_pga").equals("0")){
                //烈度
                int index = url.lastIndexOf("/");
                String tempStr = url.substring(index+1);
                String code = tempStr.split("@")[0];
                code = code.replace("jc_pga","jc_ld");
                url = "map-datacenter/rest/maps/"+code+"@datacenter";
            }
            String tempLayerUrl = getSqlTempLayer(mapTemplate.getServerIpPort()+url, sb.toString(),true);
            tempLayerUrlMap.put(dictCode,tempLayerUrl);
        }else if(dictCode.equals("catalog_jjfbt")){
            //经济分布图
            String version = (String)taskObjById.get("gdp_version");
            StringBuffer sb=new StringBuffer();
            sb.append(" data_version='").append(version).append("' and del_flag='0' and st_intersects(geom, st_geomfromtext('").append(geom).append("',4490))");
            String tempLayerUrl = getSqlTempLayer(mapTemplate.getServerIpPort()+mapTemplate.getServerUrl(), sb.toString(),true);
            tempLayerUrlMap.put(dictCode,tempLayerUrl);
        }else if(dictCode.equals("catalog_rygbt")){
            //人口分布图
            String version = (String)taskObjById.get("popluation_version");
            StringBuffer sb=new StringBuffer();
            sb.append(" data_version='").append(version).append("' and del_flag='0' and st_intersects(geom, st_geomfromtext('").append(geom).append("',4490))");
            String tempLayerUrl = getSqlTempLayer(mapTemplate.getServerIpPort()+mapTemplate.getServerUrl(), sb.toString(),true);
            tempLayerUrlMap.put(dictCode,tempLayerUrl);
        }else if(dictCode.endsWith("gw")){
            //房屋数据版本
            String version = (String)taskObjById.get("house_data");
            StringBuffer sb=new StringBuffer();
            sb.append(" data_version='").append(version).append("' and del_flag='0'");
            String tempLayerUrl = getSqlTempLayer(mapTemplate.getServerIpPort()+mapTemplate.getServerUrl(), sb.toString(),true);
            tempLayerUrlMap.put(dictCode,tempLayerUrl);
        }
        return tempLayerUrlMap;
    }

    private List<String> getIntensityList(){
        return Arrays.asList("Ⅵ","Ⅶ","Ⅷ","Ⅸ","Ⅹ");
    }

    private List<String> getDestoryList(){
        return Arrays.asList("基本完好","轻微破坏","中等破坏","严重破坏","倒塌");
    }

    public Map<String,Object> getTaskObjById(String taskId){
        Map<String,Object> map = new HashMap<>();
        try{
            String sql ="select * from fxqh_calculation_tasks where id='%s'";
            sql =String.format(sql,taskId);
            map = jdbcTemplate.queryForMap(sql);
        } catch (EmptyResultDataAccessException e) {
            e.printStackTrace();
        }
        return map;
    }
    @Override
    public Map<String,Object> getSmxTaskObjById(String taskId){
        Map<String,Object> map = new HashMap<>();
        try{
            String sql ="select * from fxqh_lifeline_task where id='%s'";
            sql =String.format(sql,taskId);
            map = jdbcTemplate.queryForMap(sql);
        } catch (EmptyResultDataAccessException e) {
            e.printStackTrace();
        }
        return map;
    }

    //根据数据类型、任务ID获取临时图层URL
    public String getTempLayerUrlByDataType(String dataType,LegendVo legendVo){
        String tempLayerUrl = "";
        String layerUrl = "";
        String sqlText = "";
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String url = configGroup.getProperty("supergraphRestTemplateUrl");
        if (PlatformObjectUtils.isNotEmpty(layerUrl) && PlatformObjectUtils.isNotEmpty(sqlText)) {
            //获取临时图层
            tempLayerUrl = getSqlTempLayer(layerUrl, sqlText,true);
            System.out.println(dataType+"临时图层："+tempLayerUrl);
        }
        return tempLayerUrl;
    }


    //获取临时图层url
    private String getSqlTempLayer(String layerUrl, String sqlText,boolean showLabelBool) {
        String resultUrl = layerUrl;
        if (PlatformObjectUtils.isNotEmpty(sqlText)) {
            JSONArray jsonArray = getLayersRJson(layerUrl);
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONArray layers = jsonArray.getJSONObject(i).getJSONObject("subLayers").getJSONArray("layers");
                for(int j=0;j<layers.size();j++){
                    JSONObject layer = layers.getJSONObject(j);
                    layer.put("displayFilter",sqlText);
                    if(showLabelBool==false && layer.getString("ugcLayerType")=="THEME"){
                        if(layer.getJSONObject("theme").getString("type")=="LABEL"){//文字标签子图层
                            layer.put("visible",showLabelBool);
                        }
                    }
                }
            }
            String jsonStr = JSON.toJSONString(jsonArray);
            JSONObject resultObj = postTempLayersSet(layerUrl,jsonStr);
            String newResourceID = resultObj.getString("newResourceID");
            String newResourceLocation = resultObj.getString("newResourceLocation");
            if (PlatformObjectUtils.isNotEmpty(newResourceLocation)) {
                resultUrl = newResourceLocation.replace(".rjson","");
            }
        }
        return resultUrl;
    }

    private JSONArray getLayersRJson(String layerUrl) {
        try {
            String dataUrl = layerUrl + "/layers.rjson";
            if(layerUrl.indexOf("tempLayersSet")!=-1){
                dataUrl = layerUrl + ".rjson";//临时图层
            }
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return null;
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(new JSONObject(), headers);
            ResponseEntity<String> exchange = restTemplate.exchange(dataUrl, HttpMethod.GET, entity, String.class);
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(exchange));
            JSONArray body = JSON.parseArray(jsonObject.getString("body"));
            if (body == null) {
                return null;
            }
            return body;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    private JSONObject postTempLayersSet(String layerUrl, String jsonStr){
        JSONObject result = new JSONObject();
        String dataUrl = layerUrl + "/tempLayersSet.rjson";
        try {
            dataUrl = URLDecoder.decode(dataUrl, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
        dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");

        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json; charset=UTF-8");

        HttpEntity<String> entity = new HttpEntity<>(jsonStr, headers);
        ResponseEntity<String> exchange = restTemplate.exchange(dataUrl, HttpMethod.POST, entity, String.class);
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(exchange));
        JSONObject body = JSON.parseObject(jsonObject.getString("body"));
        if (body == null) {
            return null;
        }
        result = body;

        return result;
    }

    //获取DEM图层名称列表
    public List<String> getDEMlayerNameList(String taskDistrict){
        List<String> nameList = new ArrayList<>();
        //DEM图层名
        String tempsql = "";
        String[] district = taskDistrict.split("、");
        List<String> provinceList = new ArrayList<>();
        for(int i=0;i<district.length;i++){
            String[] strArr = district[i].split("-");
            if(strArr.length>0){
                //正常
            }else{
                continue;
            }
            if (PlatformObjectUtils.isNotEmpty(tempsql)) {
                tempsql += " or ";
            }
            String province = strArr[0];
            if(!provinceList.contains(province)){
                provinceList.add(province);
            }
            tempsql += "(province='"+province+"'";
            if(province.equals("北京市") || province.equals("天津市") || province.equals("上海市") || province.equals("重庆市")){
                tempsql += " and city='"+province+"'";
                if(strArr.length>1){
                    tempsql += " and area='"+strArr[1]+"'";
                }else{
                    tempsql += " and area=''";
                }
            }else{
                if(strArr.length>1){
                    tempsql += " and city='"+strArr[1]+"'";
                }else{
                    tempsql += " and city=''";
                }
                if(strArr.length>2){
                    tempsql += " and area='"+strArr[2]+"'";
                }else{
                    tempsql += " and area=''";
                }
            }
            tempsql += ")";
        }
        if(provinceList.size()>0){
            for(int i=0;i<provinceList.size();i++){
                String province = provinceList.get(i);
                if (PlatformObjectUtils.isNotEmpty(tempsql)) {
                    tempsql += " or ";
                }
                tempsql += "(province='"+province+"' and city='' and area='')";
            }
        }
        //查询DEM高程文件图层名称
        String sql = "SELECT affiliated_file_name FROM qh_map_files where type='地形地貌（高程）_' and is_delete='0' and ("+tempsql+")";
        List<String> list = jdbcTemplate.queryForList(sql, String.class);
        for(int i=0;i<list.size();i++){
            String name = list.get(i);
            nameList.add(name);
        }

        return nameList;
    }


//    //构造人口图片数据
//    @Override
//    public Map<String,String>  buildPopulationDataGraphParamData(String taskId){
//        String dictCode="catalog_rygbt";
//        LegendVo legendVo= new LegendVo();
//        return getCommonDataMapParamData(taskId,dictCode,legendVo,"");
//    }

//    /**
//     *
//     * @param taskId
//     * @return
//     */
//    @Override
//    public Map<String,String>  buildGDPDataGraphParamData(String taskId){
//        String dictCode="catalog_jjfbt";
//        LegendVo legendVo= new LegendVo();
//        return getCommonDataMapParamData(taskId,dictCode,legendVo,"");
//    }
//    @Override
//    public Map<String,String>  buildAdministrativeMapGraphParamData(String taskId){
//        String dictCode="catalog_xzqht";
//        LegendVo legendVo = new LegendVo();
//        return getCommonDataMapParamData(taskId,dictCode,legendVo,"");
//    }

    //用URLEncode编码，防止如%符号不能打印
    public String setStringEncoder(String string) {
        String stringEncoder = string;
        try{
            stringEncoder = URLEncoder.encode(string,"UTF-8");
        }catch (Exception e){
            e.printStackTrace();
        }

        return stringEncoder;
    }
    /**
     * 抽取公共的方法
     * @param taskId
     * @param dictCode
     * @param legendVo
     * @return
     */
    @Override
    public Map<String,String> getCommonDataMapParamData(String taskId, String dictCode, LegendVo legendVo,String flag,String type) throws Exception {
        System.out.println("生成超图dictcode========"+dictCode+"====任务id为===="+taskId);
        if(legendVo==null){
            legendVo=new LegendVo();
        }
        MapTemplate mapTemplate = new MapTemplate();

        //String dictCode="czqtjglxgw";
        mapTemplate = getMapTemplateData(dictCode,flag);
        legendVo.setMapTemplate(mapTemplate);

//        Map<String,Object> paramMap = getProvinceCityCountyDataQueryParam(taskId);
//        String extent = getExtent(paramMap);
//        String center = getCenter(paramMap);

        String extent = "";
        String center = "";
        if("5".equals(type) || "6".equals(type)){
            String catalogName = mapTemplate.getCatalogName();
            List<Integer> catalogNameList = new ArrayList<>();
            //if(catalogName.indexOf("_")>0){
                if(dictCode.contains("smx_expire_")){
                    String[] split = catalogName.split("_");
                    for (String s : split) {
                        if(!"yxc".equals(s)){
                            catalogNameList.add(Integer.parseInt(s));
                        }
                    }
                }else{
                    catalogName = catalogName.split("_")[0];
                    catalogNameList.add(Integer.parseInt(catalogName));
                }
            //}
            extent = estimateRepository.getExtentGeomByTaskIdAndType(taskId, catalogNameList,"fxqh_smx_evaluation_results");
            if(StringUtils.isBlank(extent)){
                extent = estimateRepository.getExtentGeomByTaskIdAndType(taskId, catalogNameList,"fxqh_smx_evaluation_results_line");
            }
            center = estimateRepository.getCenterGeomByTaskIdAndType(taskId, catalogNameList,"fxqh_smx_evaluation_results");
            if(StringUtils.isBlank(center)){
                center = estimateRepository.getCenterGeomByTaskIdAndType(taskId, catalogNameList,"fxqh_smx_evaluation_results_line");
            }
        }else{
            if("catalog_yxc".equals(dictCode)){
                Map<String,Object> taskObjById = getTaskObjById(taskId);
                String dataVersion = taskObjById.get("influence_field_version").toString();
                extent = getExtent(dataVersion);
                center = getCenter(dataVersion);
            }else{
                List<PCC> pccList = getPCCDataQueryParam(taskId);
                extent = getExtent(pccList);
                center = getCenter(pccList);
            }

        }

        if(PlatformObjectUtils.isEmpty(center) || PlatformObjectUtils.isEmpty(extent)){
            log.error("center or extent is null");
            return null ;
        }
        String[] split = extent.substring(4, extent.length() - 1).split(",");
        String[] s1 = split[0].split(" ");
        String[] s2 = split[1].split(" ");
        String leftX = s1[0];
        String leftY = s1[1];
        String rightX = s2[0];
        String rightY = s2[1];

        String format = legendVo.getMapTemplate().getFormat();
        String formatType = "横版";//测试横版
        if(format.equals("0")){//0横板
            formatType = "横版";//测试横版
        }else if(format.equals("1")){//1竖版
            formatType = "竖版";//测试竖版
        }
        int level = getLevel(Double.valueOf(leftX), Double.valueOf(leftY), Double.valueOf(rightX), Double.valueOf(rightY),formatType);
        String[] s = center.substring(6, center.length() - 1).split(" ");
        String centerX = s[0];
        String centerY = s[1];
        Map<String, Double> hashMap = new HashMap<>();
        hashMap.put("leftX", Double.valueOf(leftX));
        hashMap.put("leftY", Double.valueOf(leftY));
        hashMap.put("rightX", Double.valueOf(rightX));
        hashMap.put("rightY", Double.valueOf(rightY));
        hashMap.put("centerX", Double.valueOf(centerX));
        hashMap.put("centerY", Double.valueOf(centerY));
        hashMap.put("level", Double.valueOf(level));


        legendVo.setUnit("制图单位ABC");
//        legendVo.setSummaryText("摘要Text");
        String title = setStringEncoder(mapTemplate.getDictName());
        legendVo.setTitle(title);
        RequestVO requestVO = getRequestVO(legendVo,hashMap,taskId,type);

        RestResponse restResponse =  generateGraph(requestVO,taskId,mapTemplate);
        Map<String,String> resultMap = new HashMap<>();
        if(restResponse!=null && PlatformObjectUtils.isNotEmpty(restResponse.getData())){
            resultMap.put("fileId",restResponse.getData().toString());
            resultMap.put("imageName",mapTemplate.getDictCode());
        }
        return resultMap;
    }

    @Override
    //概率评估T年方法
    public List<Map<String,String>> getCommonDataMapParamDataPlus(String taskId, String dictCode, String[] years,String type) throws Exception {
        System.out.println("生成超图dictcode========"+dictCode+"====任务id为===="+taskId);
        LegendVo legendVo=new LegendVo();
        MapTemplate mapTemplate = new MapTemplate();

        //String dictCode="czqtjglxgw";
        mapTemplate = getMapTemplateData(dictCode,"4");
        legendVo.setMapTemplate(mapTemplate);

//        Map<String,Object> paramMap = getProvinceCityCountyDataQueryParam(taskId);
//        String extent = getExtent(paramMap);
//        String center = getCenter(paramMap);
//        List<PCC> pccList = getPCCDataQueryParam(taskId);
//        String extent = getExtent(pccList);
//        String center = getCenter(pccList);
        String extent = "";
        String center = "";
        if("".equals(dictCode)){
            Map<String,Object> taskObjById = getTaskObjById(taskId);
            String dataVersion = taskObjById.get("influence_field_version").toString();
            extent = getExtent(dataVersion);
            center = getCenter(dataVersion);
        }else{
            List<PCC> pccList = getPCCDataQueryParam(taskId);
            extent = getExtent(pccList);
            center = getCenter(pccList);
        }

        if(PlatformObjectUtils.isEmpty(center) || PlatformObjectUtils.isEmpty(extent)){
            log.error("center or extent is null");
            return null ;
        }
        String[] split = extent.substring(4, extent.length() - 1).split(",");
        String[] s1 = split[0].split(" ");
        String[] s2 = split[1].split(" ");
        String leftX = s1[0];
        String leftY = s1[1];
        String rightX = s2[0];
        String rightY = s2[1];

        String format = legendVo.getMapTemplate().getFormat();
        String formatType = "横版";//测试横版
        if(format.equals("0")){//0横板
            formatType = "横版";//测试横版
        }else if(format.equals("1")){//1竖版
            formatType = "竖版";//测试竖版
        }
        int level = getLevel(Double.valueOf(leftX), Double.valueOf(leftY), Double.valueOf(rightX), Double.valueOf(rightY),formatType);
        String[] s = center.substring(6, center.length() - 1).split(" ");
        String centerX = s[0];
        String centerY = s[1];
        Map<String, Double> hashMap = new HashMap<>();
        hashMap.put("leftX", Double.valueOf(leftX));
        hashMap.put("leftY", Double.valueOf(leftY));
        hashMap.put("rightX", Double.valueOf(rightX));
        hashMap.put("rightY", Double.valueOf(rightY));
        hashMap.put("centerX", Double.valueOf(centerX));
        hashMap.put("centerY", Double.valueOf(centerY));
        hashMap.put("level", Double.valueOf(level));

        legendVo.setUnit("制图单位ABC");
//        legendVo.setSummaryText("摘要Text");
        String title = setStringEncoder(mapTemplate.getDictName());
        legendVo.setTitle(title);
        List<Map<String,String>> lisMap=new ArrayList<>();

        for (int i = 0; i < years.length; i++) {
            legendVo.setYear(years[i]);
            String newTitle = setStringEncoder(years[i]+mapTemplate.getDictName());
            legendVo.setTitle(newTitle);
            RequestVO requestVO = getRequestVO(legendVo,hashMap,taskId,type);

            RestResponse restResponse =  generateGraphPlus(requestVO,taskId,mapTemplate,i);
            Map<String,String> resultMap = new HashMap<>();
            if(restResponse!=null && PlatformObjectUtils.isNotEmpty(restResponse.getData())){
                resultMap.put("fileId",restResponse.getData().toString());
                resultMap.put("imageName",mapTemplate.getDictCode()+"_"+i);
            }
            lisMap.add(resultMap);
        }
        return lisMap;
    }

    public RestResponse generateGraphPlus(RequestVO requestVO,String taskId,MapTemplate mapTemplate,int years) {
        String fileName = mapTemplate.getDictCode()+"_"+years;
        RestResponse restResponse = null;
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String url = configGroup.getProperty("supergraphRestTemplateUrl") + "/webprinting/rest/webprinting/v1/jobs.json";
        JSONObject requestJsonVo = (JSONObject) JSONObject.toJSON(requestVO);
        String json = JSONObject.toJSONString(requestJsonVo);
        log.info(json);
        Map map = JSONObject.parseObject(json, Map.class);
        ResponseEntity<String> stringResponseEntity = restTemplateUtil.sendPostHttpRequest(url, map);
        String body = stringResponseEntity.getBody();
        System.out.println("超图任务taskid"+taskId+",接口返回数据================="+body);
        List<ResponseVO> responseVO = JSON.parseArray(body, ResponseVO.class);
        String path = "";
        if (responseVO != null || responseVO.size() > 0) {
            path = responseVO.get(0).getPath();
            //获取出图任务状态
            path = getMapLayerPrintJob(path);
            if(path.equals("出图失败")){
                return RestResponse.fail("出图失败！");
            }
            path = responseVO.get(0).getPath() + "/" + "result";
            String savePath = ctLocalDir;
            path = path.replace("@", "%40");
            System.out.println("路径  " + path);
            restResponse = downloadsFile.downloadByUrl(path, savePath,taskId,fileName,mapTemplate.getFlag());
        }
        File file = new File(ctLocalDir);
        File[] files = file.listFiles();
        for (File file1 : files) {
            if (file1.isFile()) {
                file1.delete();
            }
        }

        return restResponse;
    }

}
